package mamikeji.liaowa.ui.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.wang.avi.AVLoadingIndicatorView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import mamikeji.liaowa.R;
import mamikeji.liaowa.application.MyApplication;
import mamikeji.liaowa.bean.ApkBean;
import mamikeji.liaowa.bean.EventDetailsBean;
import mamikeji.liaowa.bean.MainBean;
import mamikeji.liaowa.bean.PushMessage;
import mamikeji.liaowa.bean.Wa_Main_ListBean;
import mamikeji.liaowa.bean.WeatherBean;
import mamikeji.liaowa.bean.Web_forum_changeBean;
import mamikeji.liaowa.db.PushMessageManager;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.article.ArticleTypeActivity;
import mamikeji.liaowa.ui.activity.circle.BabyMomCircleActivity;
import mamikeji.liaowa.ui.activity.circle.MyCircleActivity;
import mamikeji.liaowa.ui.activity.circle.PublishCircleActivity;
import mamikeji.liaowa.ui.activity.clock.ClockListActivity;
import mamikeji.liaowa.ui.activity.clock.ClockTypeActivity;
import mamikeji.liaowa.ui.activity.diary.EveryDayDiaryActivity;
import mamikeji.liaowa.ui.activity.diary.PublishDiaryActivity;
import mamikeji.liaowa.ui.activity.forum.MyForumActivity;
import mamikeji.liaowa.ui.activity.forum.PublishForumActivity;
import mamikeji.liaowa.ui.activity.notice.UserNoticeActivity;
import mamikeji.liaowa.ui.activity.right.BabyMSGActivity;
import mamikeji.liaowa.ui.activity.right.EventDetailsActivity;
import mamikeji.liaowa.ui.activity.right.TimeDateActivity;
import mamikeji.liaowa.ui.activity.right.UserCollectionActivity;
import mamikeji.liaowa.ui.activity.right.UserFeedbackActivity;
import mamikeji.liaowa.ui.activity.right.UserFollowActivity;
import mamikeji.liaowa.ui.activity.right.UserIdentityActivity;
import mamikeji.liaowa.ui.activity.right.UserMSGActicity;
import mamikeji.liaowa.ui.activity.right.setting.SetActivity;
import mamikeji.liaowa.ui.adapter.MainFragmentAdapter;
import mamikeji.liaowa.ui.adapter.Main_EventViewPagerAdapter;
import mamikeji.liaowa.ui.adapter.Main_TodoAdapter;
import mamikeji.liaowa.ui.adapter.Main_changeWaAdapter;
import mamikeji.liaowa.ui.fragment.main_date.Main_CircleFragment;
import mamikeji.liaowa.ui.fragment.main_date.Main_ForumFragment;
import mamikeji.liaowa.ui.fragment.main_todo.ToDo_RecyclerFragment;
import mamikeji.liaowa.ui.fragment.main_todo.ToDo_SeekBarFragment;
import mamikeji.liaowa.utils.DownLoadVideo;
import mamikeji.liaowa.utils.ExampleUtil;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MultiStateView;
import mamikeji.liaowa.widget.DiffuseView;
import mamikeji.liaowa.widget.GlideCircleTransform;
import mamikeji.liaowa.widget.ResideMenu.ResideMenu;
import mamikeji.liaowa.widget.ZoomOutPageTransformer;
import mamikeji.liaowa.widget.clock.Model.AlarmModel;
import mamikeji.liaowa.widget.clock.data.MyAlarmDataBase;
import mamikeji.liaowa.widget.datepicker.MonthDateView;
import mamikeji.liaowa.widget.floatingactionbutton.FloatingActionButton;
import mamikeji.liaowa.widget.floatingactionbutton.FloatingActionsMenu;
import mamikeji.liaowa.widget.roundvideo.MyVideoView;
import mamikeji.liaowa.widget.wave.WaveHelper;
import mamikeji.liaowa.widget.wave.WaveView;

public class MainActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";

    private static final int TAG_CIRCLE = 1001;
    private static final int TAG_FORUM = 1002;

    private static final int TAG_PUBLISH_CIRCLE = 1003;
    private static final int TAG_PUBLISH_FORUM = 1004;

    @BindView(R.id.textView_main_top_changewa)
    TextView textView_main_top_changewa;
    @BindView(R.id.linearLayout_main_top_left)
    LinearLayout linearLayout_main_top_left;
    @BindView(R.id.linearLayout_main_top_right)
    RelativeLayout linearLayout_main_top_right;
    @BindView(R.id.imageView_main_top_weather)
    ImageView imageView_main_top_weather;
    @BindView(R.id.textView_main_top_weather)
    TextView textView_main_top_weather;
    @BindView(R.id.relativeLayout_main_top_header)
    RelativeLayout relativeLayout_main_top_header;
    @BindView(R.id.relativeLayout_main_top_video)
    RelativeLayout relativeLayout_main_top_video;
    @BindView(R.id.imageView_main_top_liao)
    ImageView imageView_main_top_liao;
    @BindView(R.id.relativeLayout_main_top_headerimg)
    RelativeLayout relativeLayout_main_top_headerimg;
    @BindView(R.id.textView_main_yangyu_time)
    TextView textView_main_yangyu_time;
    @BindView(R.id.textView_main_birth_query)
    TextView textView_main_birth_query;
    @BindView(R.id.textView_main_birth_query_count)
    TextView textView_main_birth_query_count;
    @BindView(R.id.relativeLayout_main_birth_query)
    RelativeLayout relativeLayout_main_birth_query;
    @BindView(R.id.relativeLayout_main_birth)
    RelativeLayout relativeLayout_main_birth;
    @BindView(R.id.textView_main_yun_time)
    TextView textView_main_yun_time;
    @BindView(R.id.textView_main_yunyu_describe)
    TextView textView_main_yunyu_describe;
    @BindView(R.id.textView_main_yun_endtime_1)
    TextView textView_main_yun_endtime_1;
    @BindView(R.id.textView_main_yun_endtime_2)
    TextView textView_main_yun_endtime_2;
    @BindView(R.id.textView_main_yun_endtime_3)
    TextView textView_main_yun_endtime_3;
    @BindView(R.id.relativeLayout_main_yunyu)
    RelativeLayout relativeLayout_main_yunyu;
    @BindView(R.id.textView_main_yangyu_height)
    TextView textView_main_yangyu_height;
    @BindView(R.id.textView_main_yangyu_width)
    TextView textView_main_yangyu_width;
    @BindView(R.id.textView_main_yangyu_describe)
    TextView textView_main_yangyu_describe;
    @BindView(R.id.linearLayout_main_yangyu)
    LinearLayout linearLayout_main_yangyu;
    @BindView(R.id.main_wave_header_bottom)
    WaveView main_wave_header_bottom;
    @BindView(R.id.waveView_index)
    WaveView waveView_index;
    @BindView(R.id.relativeLayout_main_waveView)
    RelativeLayout relativeLayout_main_waveView;
    @BindView(R.id.textView_main_todayIndex)
    TextView textView_main_todayIndex;
    @BindView(R.id.vp_main_header_todo)
    ViewPager vp_main_header_todo;
    @BindView(R.id.linearLayout_main_header_todo)
    LinearLayout linearLayout_main_header_todo;
    @BindView(R.id.linearLayout_main_header_everydiary)
    LinearLayout linearLayout_main_header_everydiary;
    @BindView(R.id.linearLayout_main_header_clock)
    LinearLayout linearLayout_main_header_clock;
    @BindView(R.id.linearLayout_main_header_momcircle)
    LinearLayout linearLayout_main_header_momcircle;
    @BindView(R.id.linearLayout_main_header_article)
    LinearLayout linearLayout_main_header_article;
    @BindView(R.id.textView_main_event_index)
    TextView textView_main_event_index;
    @BindView(R.id.textView_main_event_maxnum)
    TextView textView_main_event_maxnum;
    @BindView(R.id.viewPager_main_event)
    ViewPager viewPager_main_event;
    @BindView(R.id.linearLayout_main_article)
    LinearLayout linearLayout_main_article;
    @BindView(R.id.banner_main_event)
    Banner banner_main_event;//首页活动轮播
    @BindView(R.id.linearLayout_main_event)
    LinearLayout linearLayout_main_event;
    @BindView(R.id.frameLayout_main_fab_bg)
    FrameLayout frameLayout_main_fab_bg;
    @BindView(R.id.action_d)
    FloatingActionButton action_d;
    @BindView(R.id.action_a)
    FloatingActionButton action_a;
    @BindView(R.id.action_b)
    FloatingActionButton action_b;
    @BindView(R.id.action_c)
    FloatingActionButton action_c;
    @BindView(R.id.multiple_actions)
    FloatingActionsMenu multiple_actions;
    @BindView(R.id.multiple_action_main)
    FloatingActionButton multiple_action_main;
    @BindView(R.id.multiStateView_main)
    MultiStateView multiStateViewMain;
    @BindView(R.id.imageView_first_course)
    ImageView imageViewFirstCourse;
    @BindView(R.id.relativeLayout_first_course)
    RelativeLayout relativeLayoutFirstCourse;
    @BindView(R.id.videoView_main_top_xiu)
    MyVideoView videoViewMainTopXiu;
    @BindView(R.id.imageView_main_top_xiu_bg)
    ImageView imageViewMainTopXiuBg;
    @BindView(R.id.avi_video)
    AVLoadingIndicatorView aviVideo;
    @BindView(R.id.imageView_main_top_xiu)
    DiffuseView imageViewMainTopXiu;
    @BindView(R.id.viewPager_main_listdate)
    ViewPager viewPagerMainListdate;
    @BindView(R.id.linearLayout_main_header_yes_wa)
    LinearLayout linearLayoutMainHeaderYesWa;
    @BindView(R.id.textView_main_header_nowa_addwa)
    TextView textViewMainHeaderNowaAddwa;
    @BindView(R.id.linearLayout_main_header_no_wa)
    LinearLayout linearLayoutMainHeaderNoWa;
    @BindView(R.id.relativeLayout_main_header_todo)
    RelativeLayout relativeLayoutMainHeaderTodo;
    @BindView(R.id.linearLayout_main_header_open)
    LinearLayout linearLayoutMainHeaderOpen;
    @BindView(R.id.toolbar_tab_main)
    TabLayout toolbarTabMain;

    /**
     * 侧边栏
     */
    ImageView imageViewRightBack;//侧边栏--返回键
    SimpleDraweeView imageViewRightHeaderimg;//侧边栏--头像
    TextView textViewRightUserName;//侧边栏--用户昵称
    TextView textViewRightBabytime;//侧边栏--默选孩子阶段提示语
    TextView textView_right_my_circle;//侧边栏--每日随笔数量
    TextView textViewRightCollectionNum;//侧边栏--收藏数量
    RelativeLayout relativeLayoutRightmenuMycollection;//侧边栏--收藏
    RelativeLayout relativeLayoutRightmenuEvent;//侧边栏--我的活动
    RelativeLayout relativeLayoutRightmenuMyshare;//侧边栏--分享app
    RelativeLayout relativeLayoutRightmenuThink;//侧边栏--关于
    RelativeLayout relativeLayoutRightmenuSet;//侧边栏--设置
    FrameLayout frameLayoutRightmenuNotice;//侧边栏--消息提醒
    public TextView textViewRightFollow;//侧边栏--关注数
    TextView textViewRightFans;//侧边栏--粉丝数
    RelativeLayout relativeLayoutRightUser;//侧边栏--用户信息
    RelativeLayout relativeLayoutRightLogin;//侧边栏--登陆按钮
    TextView textViewRightmenuMsg;//侧边栏--登陆提示语
    RelativeLayout relativeLayout_rightmenu_myshare_login;//侧边栏--未登录分享
    RelativeLayout relativeLayout_rightmenu_think_login;//侧边栏--未登录意见反馈
    RelativeLayout relativeLayout_rightmenu_set_login;//侧边栏--未登录设置
    RelativeLayout relativeLayout_right_login_btn;//侧边栏--未登录按钮
    ImageView imageView_rightmenu_notice;
    LinearLayout linearLayoutRightmenuGuanzhu;//侧边栏--关注
    LinearLayout linearLayoutRightmenuUsermsg;//侧边栏--个人信息
    LinearLayout linearLayoutRightmenuFans;//侧边栏--粉丝
    RelativeLayout relativeLayout_rightmenu_forum;
    RelativeLayout relativeLayout_right_identity;//侧边栏--认证中心
    ImageView imageView_right_user_identity;//侧边栏--认证标识
    TextView textView_right_my_forum;//侧边栏--我的话题数量

    //加号遮罩层
    private boolean bool_main_fab_bg = false;

    //定位器
    private LocationManager locationManager;

    /**
     * 修一修视频弹框版
     */
    private MyVideoView jcVideoPlayer_main;

    /**
     * 水波纹管理器
     */
    private WaveHelper mWaveHelper, waveHelper_index;

    //切换娃弹框
    Dialog dialog_wa, dialog_video, dialog_apk;

    //孩子状态true为图片可跳转，false为视频不可跳转
    boolean bool_liao_states = false;

    //listviewitem点击减掉的头部数目
    private int num_listItem = 5;

    //首页信息实体类
    private MainBean mainBean;

    String wa_id;

    // 设置每日任务启动项
    private int vp_todo_index = 0;

    //每日任务适配器
    Main_TodoAdapter main_todoAdapter;

    //任务集
    List<Fragment> fragmentList = new ArrayList<>();

    //选择娃
    private List<Wa_Main_ListBean.UserbadyListBean> waBeanList;
    //选择娃适配器
    private Main_changeWaAdapter mainChangeWaAdapter;

    /**
     * 设置侧边栏
     */
    private ResideMenu resideMenu;
    private Dialog dialog_share;//分享弹框

    //版本更新实体类
    private ApkBean apkBean;

    private static final int MSG_SET_TAG = 1001;
    private static final int MSG_SET_ALIAS = 1002;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_TAG:
                    ForLog.i(TAG, "Set jp_tag in handler.");
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setTags(getApplicationContext(),
                            stringSet,
                            mTagCallback);

                    break;
                //设置标签，唯一标示
                case MSG_SET_ALIAS:
                    ForLog.i(TAG, "Set jp_tag in handler.");
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAlias(getApplicationContext(),
                            jp_alias,
                            mAliasCallback);
                    break;
                default:
                    ForLog.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getBase();
        ButterKnife.bind(this);
        setUpMenu();
        init();
        initData();
        //判断是否第一次，启动软件
        relativeLayoutFirstCourse.setVisibility(ForPreference.getBoolean(ForContents.APP_FIRST_COURSE) ? View.GONE : View.VISIBLE);
        //记录用户启动
        ForPreference.putBoolean(ForContents.APP_FIRST_COURSE, true);
        ForLog.i("asdUSER_CODE", "asdUSER_CODE  " + ForPreference.getString(ForContents.USER_CODE));
        //记录用户机型
        recordPhoneMode();
        //记录APP版本号
        recordAppVersion();
        //记录用户手机系统版本
        recordPhoneSystemLevel();
    }

    /**
     * 加载布局控件
     */
    private void init() {
        /**
         * 侧边栏
         */
        imageViewRightBack = (ImageView) resideMenu.getRightMenuView().findViewById(R.id.imageView_right_back);
        imageViewRightHeaderimg = (SimpleDraweeView) resideMenu.getRightMenuView().findViewById(R.id.imageView_right_headerimg);
        textViewRightUserName = (TextView) resideMenu.getRightMenuView().findViewById(R.id.textView_right_user_name);
        textViewRightBabytime = (TextView) resideMenu.getRightMenuView().findViewById(R.id.textView_right_babytime);
        textView_right_my_circle = (TextView) resideMenu.getRightMenuView().findViewById(R.id.textView_right_my_circle);
        textViewRightCollectionNum = (TextView) resideMenu.getRightMenuView().findViewById(R.id.textView_right_collection_num);
        relativeLayoutRightmenuMycollection = (RelativeLayout) resideMenu.getRightMenuView().findViewById(R.id.relativeLayout_rightmenu_mycollection);
        relativeLayoutRightmenuEvent = (RelativeLayout) resideMenu.getRightMenuView().findViewById(R.id.relativeLayout_rightmenu_event);
        relativeLayoutRightmenuMyshare = (RelativeLayout) resideMenu.getRightMenuView().findViewById(R.id.relativeLayout_rightmenu_myshare);
        relativeLayoutRightmenuThink = (RelativeLayout) resideMenu.getRightMenuView().findViewById(R.id.relativeLayout_rightmenu_think);
        relativeLayoutRightmenuSet = (RelativeLayout) resideMenu.getRightMenuView().findViewById(R.id.relativeLayout_rightmenu_set);
        frameLayoutRightmenuNotice = (FrameLayout) resideMenu.getRightMenuView().findViewById(R.id.frameLayout_rightmenu_notice);
        textViewRightFollow = (TextView) resideMenu.getRightMenuView().findViewById(R.id.textView_right_follow);
        textViewRightFans = (TextView) resideMenu.getRightMenuView().findViewById(R.id.textView_right_fans);
        relativeLayoutRightUser = (RelativeLayout) resideMenu.getRightMenuView().findViewById(R.id.relativeLayout_right_user);
        relativeLayoutRightLogin = (RelativeLayout) resideMenu.getRightMenuView().findViewById(R.id.relativeLayout_right_login);
        textViewRightmenuMsg = (TextView) resideMenu.getRightMenuView().findViewById(R.id.textView_rightmenu_msg);
        relativeLayout_rightmenu_myshare_login = (RelativeLayout) resideMenu.getRightMenuView().findViewById(R.id.relativeLayout_rightmenu_myshare_login);
        relativeLayout_rightmenu_think_login = (RelativeLayout) resideMenu.getRightMenuView().findViewById(R.id.relativeLayout_rightmenu_think_login);
        relativeLayout_rightmenu_set_login = (RelativeLayout) resideMenu.getRightMenuView().findViewById(R.id.relativeLayout_rightmenu_set_login);
        relativeLayout_right_login_btn = (RelativeLayout) resideMenu.getRightMenuView().findViewById(R.id.relativeLayout_right_login_btn);
        imageView_rightmenu_notice = (ImageView) resideMenu.getRightMenuView().findViewById(R.id.imageView_rightmenu_notice);
        linearLayoutRightmenuGuanzhu = (LinearLayout) resideMenu.getRightMenuView().findViewById(R.id.linearLayout_rightmenu_guanzhu);
        linearLayoutRightmenuUsermsg = (LinearLayout) resideMenu.getRightMenuView().findViewById(R.id.linearLayout_rightmenu_usermsg);
        linearLayoutRightmenuFans = (LinearLayout) resideMenu.getRightMenuView().findViewById(R.id.linearLayout_rightmenu_fans);
        relativeLayout_rightmenu_forum = (RelativeLayout) resideMenu.getRightMenuView().findViewById(R.id.relativeLayout_rightmenu_forum);
        relativeLayout_right_identity = (RelativeLayout) resideMenu.getRightMenuView().findViewById(R.id.relativeLayout_right_identity);
        imageView_right_user_identity = (ImageView) resideMenu.getRightMenuView().findViewById(R.id.imageView_right_user_identity);
        textView_right_my_forum = (TextView) resideMenu.getRightMenuView().findViewById(R.id.textView_right_my_forum);

        /**
         * 侧边栏点击
         */
        relativeLayout_right_identity.setOnClickListener(this);
        relativeLayout_rightmenu_forum.setOnClickListener(this);
        relativeLayout_rightmenu_myshare_login.setOnClickListener(this);
        relativeLayout_rightmenu_think_login.setOnClickListener(this);
        relativeLayout_rightmenu_set_login.setOnClickListener(this);
        relativeLayout_right_login_btn.setOnClickListener(this);
        imageViewRightBack.setOnClickListener(this);
        frameLayoutRightmenuNotice.setOnClickListener(this);
        imageViewRightHeaderimg.setOnClickListener(this);
        relativeLayoutRightmenuMycollection.setOnClickListener(this);
        relativeLayoutRightmenuEvent.setOnClickListener(this);
        relativeLayoutRightmenuMyshare.setOnClickListener(this);
        relativeLayoutRightmenuThink.setOnClickListener(this);
        relativeLayoutRightmenuSet.setOnClickListener(this);
        linearLayoutRightmenuGuanzhu.setOnClickListener(this);
        linearLayoutRightmenuUsermsg.setOnClickListener(this);
        linearLayoutRightmenuFans.setOnClickListener(this);

        //设置水波纹形状
        waveView_index.setShapeType(WaveView.ShapeType.CIRCLE);
        main_wave_header_bottom.setShapeType(WaveView.ShapeType.SQUARE);
        //控制水波纹
        mWaveHelper = new WaveHelper(main_wave_header_bottom);
        waveHelper_index = new WaveHelper(waveView_index);
        //设置颜色
        waveView_index.setWaveColor("#7eb9ff", "#667eb9ff");
    }

    /**
     * 初始化用户数据
     */
    private void initData() {
        //获取天气数据
        getLocation();
        /*
         * 必须事先在assets底下创建一fonts文件夹 并放入要使用的字体文件(.ttf)
         * 并提供相对路径给creatFromAsset()来创建Typeface对象
         */
        Typeface fontFace = Typeface.createFromAsset(getAssets(),
                "fonts/main_text_css.ttf");

        textView_main_todayIndex.setTypeface(fontFace);
        textViewRightmenuMsg.setTypeface(fontFace);//侧边栏，未登录介绍

        if (ForPreference.getString(ForContents.USER_PHONE).equals("") ||
                ForPreference.getString(ForContents.USER_PHONE) == null) {
            multiStateViewMain.setViewState(MultiStateView.VIEW_STATE_CONTENT);
            //没有娃
            linearLayoutMainHeaderYesWa.setVisibility(View.GONE);
            relativeLayoutMainHeaderTodo.setVisibility(View.GONE);
            linearLayoutMainHeaderOpen.setVisibility(View.GONE);

            linearLayout_main_article.setVisibility(View.GONE);
            linearLayout_main_event.setVisibility(View.GONE);

            linearLayoutMainHeaderNoWa.setVisibility(View.VISIBLE);

            textView_main_top_changewa.setText(R.string.main_select_wa);
        } else {
            //有娃
            linearLayoutMainHeaderYesWa.setVisibility(View.VISIBLE);
            relativeLayoutMainHeaderTodo.setVisibility(View.VISIBLE);
            linearLayoutMainHeaderOpen.setVisibility(View.VISIBLE);

            linearLayout_main_article.setVisibility(View.VISIBLE);
            linearLayout_main_event.setVisibility(View.VISIBLE);

            linearLayoutMainHeaderNoWa.setVisibility(View.GONE);

            //获取闹钟数量
            initClockDate();
            //获取宝宝集合
            getListData();
            //获取首页宝宝信息
            getMainData(true);

            if (!ForPreference.getString(ForContents.USER_CODE).equals(ForPreference.getString(ForContents.APP_JPUSH_Usercode))) {
                //设置唯一标签
                getJpushAlias(ForPreference.getString(ForContents.USER_CODE));
            }
        }

        //版本更新
        getApkEdition();
        //首页fragment切换数据
        getMain_vp_frament();
        //添加监听
        initListeners();
        //根据登录方式判断侧边栏布局
        //填充折线图数据
        initViewRight();
        //侧边栏分享弹框
        getDialogShare();

    }

    Main_ForumFragment main_forumFragment;
    Main_CircleFragment main_circleFragment;

    private void getMain_vp_frament() {
        List<Fragment> fragments = new ArrayList<>();

        main_forumFragment = new Main_ForumFragment();
        main_circleFragment = Main_CircleFragment.Instance("0", true);

        fragments.add(main_forumFragment);
        fragments.add(main_circleFragment);

        List<String> stringList = new ArrayList<>();
        stringList.add("热门话题");
        stringList.add("宝妈动态");

        MainFragmentAdapter mFragmentAdapteradapter = new MainFragmentAdapter(this, getSupportFragmentManager(), fragments, stringList);
        viewPagerMainListdate.setAdapter(mFragmentAdapteradapter);
        viewPagerMainListdate.setCurrentItem(0);

        viewPagerMainListdate.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener
                (toolbarTabMain));
        toolbarTabMain.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener
                (viewPagerMainListdate));

        toolbarTabMain.setupWithViewPager(viewPagerMainListdate);
        toolbarTabMain.setTabMode(TabLayout.MODE_FIXED);

        //修改tabLayout下划线的长度
        toolbarTabMain.post(new Runnable() {
            @Override
            public void run() {
                setIndicator(toolbarTabMain, 50, 50);
            }
        });

        //为tabLayout加垂直线条
        LinearLayout linearLayout = (LinearLayout) toolbarTabMain.getChildAt(0);
        linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        linearLayout.setDividerPadding(60);
        linearLayout.setDividerDrawable(ContextCompat.getDrawable(this, R.drawable.layout_divider_vertical));
    }

    /**
     * 修改tabLayout下划线的长度
     *
     * @param tabs
     * @param leftDip
     * @param rightDip
     */
    public void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());

        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }


    }

    /**
     * 实例化侧边栏
     */
    private void setUpMenu() {
        // attach to current activity;
        resideMenu = new ResideMenu(this);
        resideMenu.setUse3D(!isHUAWEI());//华为不加3D
        resideMenu.setShadowVisible(false);
        resideMenu.setBackground(R.drawable.img_gerenzhongxinbg);
        resideMenu.attachToActivity(this);
        resideMenu.setMenuListener(menuListener);
        //valid scale factor is between 0.0f and 1.0f. leftmenu'width is 150dip.
        resideMenu.setScaleValue(!isHUAWEI() ? 0.55f : 0.43f);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return resideMenu.dispatchTouchEvent(ev);
    }

    private ResideMenu.OnMenuListener menuListener = new ResideMenu.OnMenuListener() {
        @Override
        public void openMenu() {
            resideMenu.setShadowVisible(true);
        }

        @Override
        public void closeMenu() {
            resideMenu.setShadowVisible(false);
        }
    };

    /**
     * 添加监听事件
     */
    private void initListeners() {
        linearLayout_main_header_todo.setVisibility(ForPreference.getString(ForContents.USER_PHONE).equals("") ||
                ForPreference.getString(ForContents.USER_PHONE) == null ? View.VISIBLE : View.GONE);
        viewPager_main_event.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                position = position % mainBean.getHomeinfo().getHomearticles().size() + 1;
                textView_main_event_index.setText(position + "");
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

//        ptrlDownRefreshFrameLayout_main.setPtrHandler(new PtrDefaultHandler() {
//            @Override
//            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
//                return PtrDefaultHandler.checkContentCanBePulledDown(frame, listView_main_activity.getRefreshableView(), header);
//            }
//
//            @Override
//            public void onRefreshBegin(PtrFrameLayout frame) {
//                //获取宝宝集合
//                getListData();
//                //获取闹钟数量
//                initClockDate();
//                //获取首页宝宝信息
//                getMainData(true);
//                //获取首页朋友圈
//                getMain_FriendCircleData(1, 10);
//            }
//        });
        multiple_action_main.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MobclickAgent.onEvent(MainActivity.this, "HomeAddButton");//首页-添加按钮
                getGONEFab();
            }
        });

        multiStateViewMain.getView(MultiStateView.VIEW_STATE_ERROR).findViewById(R.id.button_error_refish)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        multiStateViewMain.setViewState(MultiStateView.VIEW_STATE_LOADING);
                        //获取宝宝集合
                        getListData();
                        //获取首页宝宝信息
                        getMainData(true);
                    }
                });

        //轮播活动跳转
        banner_main_event.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                MobclickAgent.onEvent(MainActivity.this, "HomeHealthToday");//首页-今日健康提醒
                EventDetailsBean eventDetailsBean = new EventDetailsBean(
                        mainBean.getDynamic().getActivitylist().get(position).getImgurl(),
                        mainBean.getDynamic().getActivitylist().get(position).getJumpurl(),
                        mainBean.getDynamic().getActivitylist().get(position).getPublishdate(),
                        mainBean.getDynamic().getActivitylist().get(position).getId(),
                        mainBean.getDynamic().getActivitylist().get(position).getShareurl(),
                        mainBean.getDynamic().getActivitylist().get(position).getTitle(),
                        mainBean.getDynamic().getActivitylist().get(position).getImgtype(),
                        mainBean.getDynamic().getActivitylist().get(position).getContent()
                );
                Intent intent = new Intent(MainActivity.this, EventDetailsActivity.class);
                intent.putExtra("ActivityBean", eventDetailsBean);
                startActivity(intent);
            }
        });

        videoViewMainTopXiu.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                imageViewMainTopXiuBg.setVisibility(View.VISIBLE);
            }
        });
    }

    /**
     * 判断用户登录方式，显示侧边栏布局
     */
    private void initViewRight() {
        if (ForPreference.getString(ForContents.USER_PHONE).equals("") || ForPreference.getString(ForContents.USER_PHONE) == null) {
            relativeLayoutRightLogin.setVisibility(View.VISIBLE);
            relativeLayoutRightUser.setVisibility(View.GONE);
        } else if (ForPreference.getString(ForContents.USER_CODE).equals("") || ForPreference.getString(ForContents.USER_CODE) == null) {
            relativeLayoutRightLogin.setVisibility(View.VISIBLE);
            relativeLayoutRightUser.setVisibility(View.GONE);
        } else {
            relativeLayoutRightLogin.setVisibility(View.GONE);
            relativeLayoutRightUser.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 弹框
     */
    public void getGONEFab() {
        bool_main_fab_bg = !bool_main_fab_bg;
        multiple_action_main.setIcon(bool_main_fab_bg ? R.drawable.icon_cha_n : R.drawable.icon_jiahao_n);
        multiple_actions.toggle();
        multiple_actions.setVisibility(bool_main_fab_bg ? View.VISIBLE : View.GONE);
        frameLayout_main_fab_bg.setVisibility(bool_main_fab_bg ? View.VISIBLE : View.GONE);
    }

    /**
     * 版本更新
     */
    public void getApkEdition() {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.APK_EDITION_currentId, getVersionName());
        formMap.put(HttpKey.APK_EDITION_apptype, ForContents.GET_2);
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.APK_EDITION, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        apkBean = new Gson().fromJson(response, ApkBean.class);
                        if (apkBean.getData().getAppstate() == 1) {
                            showAPKEditionDialog();
                            dialog_apk.show();
                        }
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                    hideLoading();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    boolean bool_downAPK = false;

    /**
     * 版本更新
     */
    private void showAPKEditionDialog() {
        dialog_apk = new Dialog(this, R.style.Dialog_APK);
        View view = LayoutInflater.from(this).inflate(R.layout.diglog_main_apk_edition, null);
        dialog_apk.setContentView(view);
        dialog_apk.setCanceledOnTouchOutside(false);
        LinearLayout linearLayout_apk_edition = (LinearLayout) view.findViewById(R.id.linearLayout_apk_edition);
        TextView textView_apk_edition_num = (TextView) view.findViewById(R.id.textView_apk_edition_num);
        TextView textView_apk_edition_counts = (TextView) view.findViewById(R.id.textView_apk_edition_counts);
        final TextView textView_apk_edition_query = (TextView) view.findViewById(R.id.textView_apk_edition_query);
        TextView textView_apk_edition_cancel = (TextView) view.findViewById(R.id.textView_apk_edition_cancel);

        textView_apk_edition_num.setText(apkBean.getData().getAppversion());
        textView_apk_edition_counts.setText(apkBean.getData().getAppdes());

        textView_apk_edition_cancel.setVisibility(apkBean.getData().getForceupdate() == 2 ?
                View.GONE : View.VISIBLE);
        linearLayout_apk_edition.setBackgroundResource(apkBean.getData().getForceupdate() == 2 ?
                R.drawable.img_gengxin_n_null : R.drawable.img_gengxin_n);

        textView_apk_edition_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String text = apkBean.getData().getAppversion().replaceAll("\\.", "");
                if (!bool_downAPK) {
                    DownLoadVideo.downAPK(MainActivity.this, apkBean.getData().getAppurl(), text, textView_apk_edition_query);
                    bool_downAPK = true;
                }
            }
        });
        textView_apk_edition_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog_apk.hide();
            }
        });
    }

    /**
     * 获取宝宝集合
     *
     * @return
     */
    public void getListData() {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.WA_LIST_USERID, ForPreference.getString(ForContents.USER_CODE));
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.USERBADY_LIST, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
//                ptrlDownRefreshFrameLayout_main.refreshComplete();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG + "_walist", response);
//                ptrlDownRefreshFrameLayout_main.refreshComplete();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        Wa_Main_ListBean waBean = new Gson().fromJson(response, Wa_Main_ListBean.class);
                        waBeanList = new ArrayList<Wa_Main_ListBean.UserbadyListBean>();
                        waBeanList.addAll(waBean.getUserbadyList());
                        ForPreference.putInt(ForContents.USER_COUNT, waBeanList.size());
                        showSelectWaDialog(waBeanList);
                    } else {
//                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 选择娃弹框
     *
     * @param userbadyList
     */
    private void showSelectWaDialog(List<Wa_Main_ListBean.UserbadyListBean> userbadyList) {
        dialog_wa = new Dialog(this, R.style.DialogLoading);
        View view = LayoutInflater.from(this).inflate(R.layout.diglog_main_qiehuanwa, null);
        dialog_wa.setContentView(view);
        ListView listView = (ListView) view.findViewById(R.id.listView_main_change_wadate);
        LinearLayout linearLayout_main_change_wa_add = (LinearLayout) view.findViewById(R.id.linearLayout_main_change_wa_add);
        mainChangeWaAdapter = new Main_changeWaAdapter(userbadyList, this);
        listView.setAdapter(mainChangeWaAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                dialog_wa.hide();
                getChangeWa_default(waBeanList.get(i).getId());
                waBeanList.add(0, waBeanList.get(i));
                waBeanList.remove(i + 1);
            }
        });

        linearLayout_main_change_wa_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, AddWaActivity.class));
            }
        });
    }

    /**
     * 更新默认娃娃
     *
     * @return
     */
    public void getChangeWa_default(int waID) {
        showLoading();
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.WA_DEFAULT_USERID, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.WA_DEFAULT_BABYID, waID + "");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.WA_DEFAULT_BODY, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG + "_aasda", response);
                hideLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        getMainData(true);
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 获取app闹钟数量
     */
    private void initClockDate() {
        MyAlarmDataBase db = new MyAlarmDataBase(getApplicationContext());
        List<AlarmModel> mAlarmList = db.getAllAlarms();

        if (mAlarmList != null && mAlarmList.size() > 0) {
            for (AlarmModel alarmModel : mAlarmList) {
                ForLog.i("getParentID", alarmModel.getTypeName());
                ForLog.i("getParentID", alarmModel.getmActive());
            }
        } else {
            ForLog.i("getParentID", "空");
        }

        List<String> stringList = new ArrayList<>();
        for (int i = 0; i < mAlarmList.size(); i++) {
            stringList.add(mAlarmList.get(i).getParentID());
        }

        stringList = removeDuplicateWithOrder(stringList);

        ForPreference.putInt(ForContents.APP_CLOCK_COUNT, stringList.size());
    }

    //去重
    public List removeDuplicateWithOrder(List list) {
        Set set = new HashSet();
        List newList = new ArrayList();
        for (Iterator iter = list.iterator(); iter.hasNext(); ) {
            Object element = iter.next();
            if (set.add(element))
                newList.add(element);
        }
        return newList;
    }

    /**
     * 获取首页宝宝信息
     *
     * @return
     */
    public void getMainData(final boolean bool) {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.MAIN_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.MAIN_DATA, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG + "getMainData", e.getMessage());
                ForToast.showToast(R.string.intent_error);
                multiStateViewMain.setViewState(MultiStateView.VIEW_STATE_NOINTERNET);
                //    ptrlDownRefreshFrameLayout_main.refreshComplete();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG + "_aasda", response);
                //    ptrlDownRefreshFrameLayout_main.refreshComplete();
                mainBean = new Gson().fromJson(response, MainBean.class);
                if (mainBean.getHomeinfo() != null && mainBean.getDynamic() != null) {
                    multiStateViewMain.setViewState(MultiStateView.VIEW_STATE_CONTENT);

                    //判断是否是刷新任务
                    //true正常加载，false只刷新任务
                    if (bool) {
                        if (mainBean.getDynamic().getBabyid() == 0) {
                            getChangeWa_default(waBeanList.get(0).getId());
                        } else {

                            if (!ForPreference.getString(ForContents.APP_JPUSH_TAG).equals(mainBean.getDynamic().getTag())) {
                                ForPreference.putString(ForContents.APP_JPUSH_TAG, mainBean.getDynamic().getTag());
                                if (ForPreference.getBoolean(ForContents.GET_NEW)) {
                                    getJpushTag(mainBean.getDynamic().getTag());
                                }
                            }

                            //判断撩动画非空
                            if (mainBean.getHomeinfo().getFileurl() != null && !mainBean.getHomeinfo().getFileurl().equals("")) {
                                if (mainBean.getHomeinfo().getFiletype() == 0) {
                                    relativeLayout_main_top_video.setVisibility(View.GONE);
                                    imageView_main_top_liao.setVisibility(View.VISIBLE);
                                    imageViewMainTopXiuBg.setVisibility(View.GONE);

                                    ForPreference.putString(ForContents.WA_headerimg_url, mainBean.getHomeinfo().getFileurl());
                                    Glide.with(MainActivity.this)
                                            .load(mainBean.getHomeinfo().getFileurl())
                                            .transform(new GlideCircleTransform(MainActivity.this))
                                            .crossFade()
                                            .error(R.drawable.img_baobaotouxiang)
                                            .into(imageView_main_top_liao);
                                } else {
                                    relativeLayout_main_top_video.setVisibility(View.VISIBLE);
                                    imageView_main_top_liao.setVisibility(View.GONE);
                                    imageViewMainTopXiuBg.setVisibility(View.VISIBLE);
                                    Glide.with(MainActivity.this)
                                            .load(mainBean.getHomeinfo().getCover())
                                            .transform(new GlideCircleTransform(MainActivity.this))
                                            .crossFade()
                                            .error(R.drawable.holder_bg)
                                            .into(imageViewMainTopXiuBg);
                                    //首页视频弹框
                                    showVideoDialog();
                                    DownLoadVideo.downVido(mainBean.getHomeinfo().getFileurl(), videoViewMainTopXiu, aviVideo);
                                }
                            }

                            //消息通知
                            getSystemMessageAndTime();

                            //判断是否切换娃
                            ForPreference.putBoolean(ForContents.WHERE_WA_ID, false);

                            //记录默选娃ID
                            ForPreference.putString(ForContents.WA_DEFAULT_ID, mainBean.getDynamic().getBabyid() + "");
                            //记录默选娃状态时间
                            ForPreference.putString(ForContents.WA_DAY, mainBean.getHomeinfo().getBabydes());
                            //记录默选娃昵称
                            ForPreference.putString(ForContents.WA_nickname, mainBean.getDynamic().getBabyname());
                            //记录默选娃状态
                            ForPreference.putString(ForContents.WA_STATIC, mainBean.getDynamic().getBabystatus() + "");
                            //记录收藏数量
                            ForPreference.putInt(ForContents.USER_COLLECTION, mainBean.getDynamic().getMycollection());
                            //用户话题数量
                            ForPreference.putInt(ForContents.USER_forum_num, mainBean.getDynamic().getTop_num());
                            //记录每日随笔数量
                            ForPreference.putInt(ForContents.USER_my_circle, mainBean.getDynamic().getMam_num());
//                    //记录今日随笔数量
//                    ForPreference.putInt(ForContents.USER_today_diary, mainBean.getDynamic().getEssaynum());
                            //记录用户粉丝
                            ForPreference.putInt(ForContents.USER_fans, mainBean.getDynamic().getFans());
                            //记录用户关注数
                            ForPreference.putInt(ForContents.USER_follow, mainBean.getDynamic().getFollow());
                            //记录娃的时间码
                            ForPreference.putString(ForContents.WA_timeCode, mainBean.getDynamic().getCode());
                            //记录消息通知数量，是否显示小红点
                            ForPreference.putInt(ForContents.APP_NOTICE_MSG, mainBean.getDynamic().getIsmessage());
                            //记录用户邀请码
                            if (mainBean.getDynamic().getActivationcode() == null || mainBean.getDynamic().getActivationcode().equals("")) {
                                ForPreference.putString(ForContents.USER_activationcode, "code_null");
                            } else {
                                ForPreference.putString(ForContents.USER_activationcode, mainBean.getDynamic().getActivationcode());
                            }

                            /**
                             * 侧边栏 控件填充数据
                             */
                            Glide
                                    .with(MainActivity.this)
                                    .load(ForPreference.getString(ForContents.USER_HEADERURL))
                                    .transform(new GlideCircleTransform(MainActivity.this))
                                    .crossFade()
                                    .error(R.drawable.img_baobaotouxiang)
                                    .into(imageViewRightHeaderimg);
//                            imageViewRightHeaderimg
//                                    .setImageURI(Uri.parse(ForPreference.getString(ForContents.USER_HEADERURL)));
                            textViewRightUserName.setText(ForPreference.getString(ForContents.USER_NAME));
                            textViewRightBabytime.setText(ForPreference.getString(ForContents.WA_DAY));
                            textView_right_my_circle.setText(ForPreference.getInt(ForContents.USER_my_circle) + "");
                            textViewRightCollectionNum.setText(ForPreference.getInt(ForContents.USER_COLLECTION) + "");
                            textViewRightFollow.setText(ForPreference.getInt(ForContents.USER_follow) + "");
                            textViewRightFans.setText(ForPreference.getInt(ForContents.USER_fans) + "");
                            imageView_right_user_identity.setImageResource(mainBean.getDynamic().getCertification_name().equals("") ?
                                    R.drawable.icon_renzheng_n : R.drawable.icon_renzheng_h);
                            textView_right_my_forum.setText(ForPreference.getInt(ForContents.USER_forum_num) + "");

                            //娃的三个状态，头部右边
                            getMainDate(mainBean);

                            //刷新默选娃
                            if (mainChangeWaAdapter != null) {
                                for (int i = 0; i < waBeanList.size(); i++) {
                                    if (ForPreference.getString(ForContents.WA_DEFAULT_ID).equals(waBeanList.get(i).getId() + "")) {
                                        waBeanList.add(0, waBeanList.get(i));
                                        waBeanList.remove(i + 1);
                                    }
                                }
                                mainChangeWaAdapter.notifyDataSetChanged();
                            }

                            textView_main_top_changewa.setText(ForPreference.getString(ForContents.WA_nickname));

                            //首页推荐文章轮播
                            if (mainBean.getHomeinfo().getHomearticles() != null) {
                                linearLayout_main_article.setVisibility(View.VISIBLE);
                                viewPager_main_event.setPageTransformer(true, new ZoomOutPageTransformer());
                                viewPager_main_event.setPageMargin(getResources().getDimensionPixelSize(R.dimen.layout_0dp));
                                viewPager_main_event.setOffscreenPageLimit(mainBean.getHomeinfo().getHomearticles().size());
                                Main_EventViewPagerAdapter mAdapter = new Main_EventViewPagerAdapter(MainActivity.this, mainBean.getHomeinfo().getHomearticles());
                                viewPager_main_event.setAdapter(mAdapter);
                                viewPager_main_event.setCurrentItem(mainBean.getHomeinfo().getHomearticles().size() * 1000 / 2);
                                textView_main_event_maxnum.setText(mainBean.getHomeinfo().getHomearticles().size() + "");
                            } else {
                                linearLayout_main_article.setVisibility(View.GONE);
                            }

                            //填充活动轮播
                            List<MainBean.DynamicEntity.ActivitylistEntity> activitylist = mainBean.getDynamic().getActivitylist();
                            if (activitylist != null) {
                                linearLayout_main_event.setVisibility(View.VISIBLE);
                                List<String> imageUrls = new ArrayList<>();
                                for (int i = 0; i < activitylist.size(); i++) {
                                    imageUrls.add(activitylist.get(i).getImgurl());
                                }
                                banner_main_event.setImageLoader(new GlideImageLoader());
                                banner_main_event.setImages(imageUrls);
                                banner_main_event.setIndicatorGravity(BannerConfig.CENTER);
                                banner_main_event.start();
                            } else {
                                linearLayout_main_event.setVisibility(View.GONE);
                            }

                        }
                    }

                    double score = mainBean.getDynamic().getTotalscore();
                    double num = score / 100;
                    waveHelper_index.setWaveIndex((float) num, 0.05f);

                    //填充待办任务
                    List<MainBean.DynamicEntity.TaskconfigEntity> taskconfigEntityList = mainBean.getDynamic().getTaskconfig();
                    if (taskconfigEntityList != null && taskconfigEntityList.size() > 0) {
                        //清空数据
                        fragmentList.clear();
                        for (int i = 0; i < taskconfigEntityList.size(); i++) {
                            //任务实体
                            MainBean.DynamicEntity.TaskconfigEntity listEntity = taskconfigEntityList.get(i);
                            if (listEntity.getType() == 1) {
                                ToDo_SeekBarFragment fragment = ToDo_SeekBarFragment.Instance(listEntity, i, taskconfigEntityList.size());
                                fragmentList.add(fragment);
                            } else {
                                ToDo_RecyclerFragment fragment = ToDo_RecyclerFragment.Instance(listEntity, i, taskconfigEntityList.size());
                                fragmentList.add(fragment);
                            }
                        }
                        //填充每日任务
                        main_todoAdapter = new Main_TodoAdapter(MainActivity.this, getSupportFragmentManager(), fragmentList);
                        vp_main_header_todo.setAdapter(main_todoAdapter);
                        vp_main_header_todo.setCurrentItem(vp_todo_index);
                    }

                    multiStateViewMain.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                } else {
//                    multiStateViewMain.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                    multiStateViewMain.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                }
            }
        });
    }

    public void getToDo_vp(int num, boolean bool) {
        if (bool) {
            double score = num;
            double position = score / 100;
            waveHelper_index.setWaveIndex((float) position, 0.05f);
        } else {
            this.vp_todo_index = num;
            getMainData(false);
        }
    }

    /**
     * 填充首页数据，判断孩子状态
     *
     * @param mainBean
     */
    private void getMainDate(MainBean mainBean) {
        textView_main_yangyu_describe.setVisibility(mainBean.getDynamic().getBabystatus() == 2 ? View.VISIBLE : View.GONE);
        imageViewMainTopXiu.setVisibility(mainBean.getDynamic().getBabystatus() != 2 ? View.VISIBLE : View.GONE);
        if (mainBean.getDynamic().getBabystatus() == 2) {
            linearLayout_main_yangyu.setVisibility(View.VISIBLE);
            relativeLayout_main_birth.setVisibility(View.GONE);
            relativeLayout_main_yunyu.setVisibility(View.GONE);

            textView_main_yangyu_time.setText(mainBean.getHomeinfo().getBabydes());
            textView_main_yangyu_describe.setText(mainBean.getHomeinfo().getTips());

            //身高，体重
            waHeight_weight(mainBean.getDynamic().getCode(),
                    mainBean.getDynamic().getSex(),
                    textView_main_yangyu_height, textView_main_yangyu_width);

            bool_liao_states = true;
        } else {
            if (280 - mainBean.getHomeinfo().getDay() <= 5) {
                linearLayout_main_yangyu.setVisibility(View.GONE);
                relativeLayout_main_birth.setVisibility(View.VISIBLE);
                relativeLayout_main_yunyu.setVisibility(View.GONE);
                //即将出生
                String nameString = getResources().getString(R.string.main_birth_prompt);
                String nameFinal = String.format(nameString, mainBean.getDynamic().getBabyname());
                textView_main_birth_query.setText(nameFinal);

                String queryString = getResources().getString(R.string.main_birth_btn);
                String queryFinal = String.format(queryString, mainBean.getDynamic().getBabyname());
                textView_main_birth_query_count.setText(queryFinal);
            } else {
                linearLayout_main_yangyu.setVisibility(View.GONE);
                relativeLayout_main_birth.setVisibility(View.GONE);
                relativeLayout_main_yunyu.setVisibility(View.VISIBLE);
                //孕育中
                textView_main_yunyu_describe.setText(mainBean.getHomeinfo().getTips());
                textView_main_yun_time.setText(mainBean.getHomeinfo().getBabydes());

                int dayNum = 280 - mainBean.getHomeinfo().getDay();

                String dayString = "";

                if (dayNum < 10) {
                    dayString = "00" + dayNum;
                } else if (dayNum < 100) {
                    dayString = "0" + dayNum;
                } else {
                    dayString = "" + dayNum;
                }

                char[] dayChars = dayString.toCharArray();

                textView_main_yun_endtime_1.setText(dayChars[0] + "");
                textView_main_yun_endtime_2.setText(dayChars[1] + "");
                textView_main_yun_endtime_3.setText(dayChars[2] + "");
            }
            bool_liao_states = false;
        }
    }

    /**
     * 视频
     */
    private void showVideoDialog() {
        dialog_video = new Dialog(this, R.style.DialogVideo);
        View view = LayoutInflater.from(this).inflate(R.layout.diglog_main_video, null);
        dialog_video.setContentView(view);
        Window window = dialog_video.getWindow();
        window.setGravity(Gravity.TOP);
        WindowManager.LayoutParams params = dialog_video.getWindow().getAttributes();
        int num = this.getWindowManager().getDefaultDisplay().getWidth();
        params.width = num;
        params.height = num;
        dialog_video.getWindow().setAttributes(params);

        jcVideoPlayer_main = (MyVideoView) view.findViewById(R.id.jcVideoPlayer_main);

        String videoUrl = "/sdcard/liaowa/liaoVideo/" +
                mainBean.getHomeinfo().getFileurl().split("/")[mainBean.getHomeinfo().getFileurl().split("/").length - 1];
        if (!new File(videoUrl).exists()) {
            videoUrl = mainBean.getHomeinfo().getFileurl();
        }
        jcVideoPlayer_main.setVideoURI(Uri.parse(videoUrl));
        jcVideoPlayer_main.start();

        jcVideoPlayer_main.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            public void onCompletion(MediaPlayer mp) {
                dialog_video.dismiss();
            }
        });
    }

    int mengbanSelector = 1;

    @OnClick({
            R.id.relativeLayout_main_top_header,
            R.id.imageView_first_course,
            R.id.linearLayout_main_top_left,
            R.id.linearLayout_main_top_right,
            R.id.frameLayout_main_fab_bg,
            R.id.action_a,
            R.id.action_b,
            R.id.action_c,
            R.id.action_d,
            R.id.linearLayout_main_header_todo,
            R.id.relativeLayout_main_birth,
            R.id.relativeLayout_main_yunyu,
            R.id.linearLayout_main_yangyu,
            R.id.relativeLayout_main_top_video,
            R.id.imageView_main_top_xiu,
            R.id.relativeLayout_main_birth_query,
            R.id.relativeLayout_main_waveView,
            R.id.linearLayout_main_header_article,
            R.id.linearLayout_main_header_clock,
            R.id.linearLayout_main_header_momcircle,
            R.id.linearLayout_main_header_everydiary,
            R.id.textView_main_header_nowa_addwa
    })
    @Override
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.relativeLayout_right_identity:
                MobclickAgent.onEvent(this, "CenterCertification");//个人中心-认证点击
                intent = new Intent(MainActivity.this, UserIdentityActivity.class);
                break;
            case R.id.textView_main_header_nowa_addwa:
                if (getJudgeLogin()) {
                    intent = new Intent(MainActivity.this, AddWaActivity.class);
                }
                break;
            case R.id.relativeLayout_main_top_header:
//                listView_main_activity.getRefreshableView().setSelection(0);
                break;
            case R.id.imageView_first_course:
                switch (mengbanSelector){
                    case 1 :
                        imageViewFirstCourse.setImageResource(R.drawable.img_course_2);
                        mengbanSelector+=1;
                        break;
                    case 2 :
                        imageViewFirstCourse.setImageResource(R.drawable.img_course_3);
                        mengbanSelector+=1;
                        break;
                    case 3 :
                        imageViewFirstCourse.setImageResource(R.drawable.img_course_4);
                        mengbanSelector+=1;
                        break;
                    case 4:
                        relativeLayoutFirstCourse.setVisibility(View.GONE);
                        break;
                }
                break;
            case R.id.linearLayout_main_header_todo:
                intent = new Intent(MainActivity.this, LoginActivity.class);
                break;
            case R.id.relativeLayout_main_birth:
            case R.id.relativeLayout_main_yunyu:
            case R.id.linearLayout_main_yangyu:
                MobclickAgent.onEvent(this, "HomeData");//首页-儿童资料
                if (getJudgeLogin()) {
                    intent = new Intent(MainActivity.this, BabyMSGActivity.class);
                    intent.putExtra(ForContents.WA_DEFAULT_ID, ForPreference.getString(ForContents.WA_DEFAULT_ID));
                }
                break;
            case R.id.relativeLayout_main_top_video:
                dialog_video.show();
                jcVideoPlayer_main.start();
                break;
            case R.id.imageView_main_top_xiu:
                MobclickAgent.onEvent(this, "HomeHoldItUp");//首页-撩一下
                imageViewMainTopXiuBg.setVisibility(View.GONE);
                imageViewMainTopXiu.start();
                int num = ForPreference.getInt(ForContents.APP_WA_LIAO);
                ForPreference.putInt(ForContents.APP_WA_LIAO, ++num);
                if (mainBean.getHomeinfo().getFiletype() == 1) {
                    videoViewMainTopXiu.start();
                }
                break;
            case R.id.relativeLayout_main_birth_query:
                MobclickAgent.onEvent(this, "HomeBirthButton");//首页-出生按钮
                if (getJudgeLogin()) {
                    showSelectedCalendarDialog(ForPreference.getString(ForContents.WA_nickname));
                }
                break;
            case R.id.action_a:
                MobclickAgent.onEvent(this, "HomeEssayWriting");//首页-写日记
                if (getJudgeLogin()) {
                    intent = new Intent(MainActivity.this, PublishDiaryActivity.class);
                }
                getGONEFab();
                break;
            case R.id.action_b:
                MobclickAgent.onEvent(this, "HomeHairDynamic");//首页-发动态
                if (getJudgeLogin()) {
                    startActivityForResult(new Intent(MainActivity.this, PublishCircleActivity.class), TAG_PUBLISH_CIRCLE);
                }
                getGONEFab();
                break;
            case R.id.action_c:
                MobclickAgent.onEvent(this, "HomeAddAlarmClock");//首页-添闹钟
                if (getJudgeLogin()) {
                    intent = new Intent(MainActivity.this, ClockTypeActivity.class);
                }
                getGONEFab();
                break;
            case R.id.action_d:
                MobclickAgent.onEvent(this, "HomeSendTopic");//首页-发话题
                if (getJudgeLogin()) {
                    startActivityForResult(new Intent(MainActivity.this, PublishForumActivity.class), TAG_PUBLISH_FORUM);
                }
                getGONEFab();
                break;
            case R.id.frameLayout_main_fab_bg:
                getGONEFab();
                break;
            case R.id.linearLayout_main_top_left:
                if (getJudgeLogin()) {
                    dialog_wa.show();
                }
                break;
            case R.id.linearLayout_main_top_right:
                MobclickAgent.onEvent(this, "HomePersonalCenterButton");//首页-个人中心按钮
                resideMenu.openMenu(ResideMenu.DIRECTION_RIGHT);
                break;
            case R.id.relativeLayout_main_waveView:
                MobclickAgent.onEvent(this, "HomeHealthIndex");//首页-健康指数
                intent = new Intent(MainActivity.this, TimeDateActivity.class);
                break;
            case R.id.linearLayout_main_header_article:
                MobclickAgent.onEvent(this, "HomeBible");//首页-撩娃宝典
                intent = new Intent(MainActivity.this, ArticleTypeActivity.class);
                break;
            case R.id.linearLayout_main_header_clock:
                MobclickAgent.onEvent(this, "HomeAlarmClock");//首页-孕育闹钟
                intent = new Intent(MainActivity.this, ClockListActivity.class);
                break;
            case R.id.linearLayout_main_header_momcircle:
                MobclickAgent.onEvent(this, "HomeMotherCircle");//首页-宝妈圈
                startActivityForResult(new Intent(MainActivity.this, BabyMomCircleActivity.class), TAG_PUBLISH_CIRCLE);
                break;
            case R.id.linearLayout_main_header_everydiary:
                MobclickAgent.onEvent(this, "HomeDailyDiary");//首页-每日日记
                intent = new Intent(MainActivity.this, EveryDayDiaryActivity.class);
                break;

            /**
             * 侧边栏
             */
            case R.id.imageView_right_back:
                resideMenu.closeMenu();
                break;
            case R.id.linearLayout_rightmenu_usermsg:
            case R.id.imageView_right_headerimg:
                MobclickAgent.onEvent(this, "CenterPersonalData");//个人中心-个人资料
                intent = new Intent(MainActivity.this, UserMSGActicity.class);
                break;
            case R.id.frameLayout_rightmenu_notice:
                MobclickAgent.onEvent(this, "CenterSystemMessage");//个人中心-系统消息
                intent = new Intent(MainActivity.this, UserNoticeActivity.class);
                break;
            case R.id.relativeLayout_rightmenu_mycollection:
                MobclickAgent.onEvent(this, "CenterMyCollection");//个人中心-我的收藏
                intent = new Intent(MainActivity.this, UserCollectionActivity.class);
                break;
            case R.id.relativeLayout_rightmenu_event:
                MobclickAgent.onEvent(this, "CenterMyDynamic");//个人中心-我的动态
                startActivityForResult(new Intent(MainActivity.this, MyCircleActivity.class), TAG_PUBLISH_CIRCLE);
                break;
            case R.id.relativeLayout_rightmenu_forum:
                MobclickAgent.onEvent(this, "CenterMyTopic");//个人中心-我的话题
                startActivityForResult(new Intent(MainActivity.this, MyForumActivity.class), TAG_PUBLISH_FORUM);
                break;
            case R.id.relativeLayout_rightmenu_myshare_login:
            case R.id.relativeLayout_rightmenu_myshare:
                MobclickAgent.onEvent(this, "CenterShare");//个人中心-分享APP
                dialog_share.show();
                break;
            case R.id.relativeLayout_rightmenu_think_login:
            case R.id.relativeLayout_rightmenu_think:
                MobclickAgent.onEvent(this, "CenterFeedback");//个人中心-意见反馈
                intent = new Intent(MainActivity.this, UserFeedbackActivity.class);
                break;
            case R.id.relativeLayout_rightmenu_set_login:
            case R.id.relativeLayout_rightmenu_set:
                MobclickAgent.onEvent(this, "CenterSettings");//个人中心-设置点击
                intent = new Intent(MainActivity.this, SetActivity.class);
                break;
            case R.id.relativeLayout_right_login_btn:
                intent = new Intent(MainActivity.this, LoginActivity.class);
                break;
            case R.id.linearLayout_rightmenu_guanzhu:
                MobclickAgent.onEvent(this, "CenterFollow");//个人中心-关注
                intent = new Intent(MainActivity.this, UserFollowActivity.class);
                intent.putExtra(ForContents.USER_follow, ForPreference.getString(ForContents.USER_CODE));
                intent.putExtra("type", true);
                intent.putExtra(ForContents.USER_NAME, ForPreference.getString(ForContents.USER_NAME));
                break;
            case R.id.linearLayout_rightmenu_fans:
                MobclickAgent.onEvent(this, "CenterFans");//个人中心-粉丝
                intent = new Intent(MainActivity.this, UserFollowActivity.class);
                intent.putExtra(ForContents.USER_follow, ForPreference.getString(ForContents.USER_CODE));
                intent.putExtra("type", false);
                intent.putExtra(ForContents.USER_NAME, ForPreference.getString(ForContents.USER_NAME));
                break;
            case R.id.linearLayout_share_wechatFriend:
                dialog_share.hide();
                ShareWeb(SHARE_MEDIA.WEIXIN);
                break;
            case R.id.linearLayout_share_wechatCircle:
                dialog_share.hide();
                ShareWeb(SHARE_MEDIA.WEIXIN_CIRCLE);
                break;
            case R.id.linearLayout_share_tencentCircle:
                dialog_share.hide();
                ShareWeb(SHARE_MEDIA.QZONE);
                break;
        }
        if (intent != null) {
            startActivity(intent);
        }
    }

    /**
     * 选择出生娃的生日
     *
     * @param name
     */
    private void showSelectedCalendarDialog(String name) {
        final Dialog dialog = new Dialog(this, R.style.DialogLoading);
        View view = LayoutInflater.from(this).inflate(R.layout.diglog_main_calendar, null);
        dialog.setContentView(view);
        TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
        TextView tv_date = (TextView) view.findViewById(R.id.tv_date);
        ImageView iv_left = (ImageView) view.findViewById(R.id.iv_left);
        ImageView iv_right = (ImageView) view.findViewById(R.id.iv_right);
        final MonthDateView monthDateView = (MonthDateView) view.findViewById(R.id.monthDateView);
        TextView tv_confirm = (TextView) view.findViewById(R.id.tv_confirm);
        monthDateView.setTextView(tv_date);
        String nameString = getResources().getString(R.string.main_selectbirth_title);
        String nameFinal = String.format(nameString, name);
        tv_title.setText(nameFinal);
        iv_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                monthDateView.onLeftClick();
            }
        });
        iv_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                monthDateView.onRightClick();
            }
        });
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String[] dateTimes = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).split("-");
                int[] dataTimeSel = monthDateView.getmSelDay();
                if (
                        Integer.parseInt(dateTimes[0]) == dataTimeSel[0] &&
                                Integer.parseInt(dateTimes[1]) == dataTimeSel[1] &&
                                Integer.parseInt(dateTimes[2]) >= dataTimeSel[2]) {
                    getChangeWa_Status(dialog, dateTimes[0] + "-" + dateTimes[1] + "-" + dateTimes[2]);
                } else {
                    ForToast.showToast("超出时间范围");
                }
            }
        });
        dialog.show();
    }

    /**
     * 修改宝宝状态，出生日期
     *
     * @return
     */
    public void getChangeWa_Status(final Dialog dialog, String birthtime) {
        showLoading();
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.UPDATE_BABYSTATUS_ID, ForPreference.getString(ForContents.WA_DEFAULT_ID));
        formMap.put(HttpKey.UPDATE_BABYSTATUS_STATUS, "2");
        formMap.put(HttpKey.UPDATE_BABYSTATUS_BIRTHTIME, birthtime);
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.UPDATE_USERBADY_STATUS, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG + "_status", e.getMessage());
                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG + "_status", response);
                hideLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        getListData();
                        getMainData(true);
                        dialog.dismiss();
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    Set<String> stringSet = new HashSet<>();

    /**
     * 设置用户极光tag
     */
    public void getJpushTag(String tag) {
        String jp_tag = tag;
        if (TextUtils.isEmpty(jp_tag)) {
            ForToast.showToast("null");
            return;
        }
        if (!ExampleUtil.isValidTagAndAlias(jp_tag)) {
            ForToast.showToast("格式内容error");
            return;
        }
        stringSet.add(jp_tag);
        // 调用 Handler 来异步设置别名
        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_TAG, jp_tag), 15000);
    }

    private final TagAliasCallback mTagCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String jp_tag, Set<String> tags) {
            String logString;
            switch (code) {
                case 0:
                    logString = "Set tag and jp_tag success";
//                    ForLog.i(TAG, logString);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    break;
                case 6002:
                    logString = "Failed to set jp_tag and tags due to timeout. Try again after 60s.";
//                    ForLog.i(TAG, logString);
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_TAG, jp_tag), 60000);
                    break;
                default:

                    logString = "Failed with errorCode = " + code;
//                    ForLog.i(TAG, logString);
            }
            ExampleUtil.showToast(logString, getApplicationContext());
        }
    };

    /**
     * 设置唯一标签
     */
    String jp_alias = "";

    /**
     * 设置用户极光tag
     */
    public void getJpushAlias(String alias) {
        //替换code中的“-”为“_”
        alias = alias.replaceAll("-", "_");

        if (TextUtils.isEmpty(alias)) {
            ForToast.showToast("null");
            return;
        }
        if (!ExampleUtil.isValidTagAndAlias(alias)) {
            ForToast.showToast("格式内容error");
            return;
        }
        jp_alias = alias;

        // 调用 Handler 来异步设置别名
        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, jp_alias), 10000);
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String jp_alias, Set<String> tags) {
            String logString;
            switch (code) {
                case 0:
                    logString = "Set tag and jp_alias success";
                    ForPreference.putString(ForContents.APP_JPUSH_Usercode, ForPreference.getString(ForContents.USER_CODE));
                    break;
                case 6002:
                    logString = "Failed to set jp_alias and tags due to timeout. Try again after 30s.";
//                    ForLog.i(TAG, logString);
                    // 延迟 30 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, jp_alias), 30000);
                    break;
                default:
                    logString = "Failed with errorCode = " + code;
//                    ForLog.i(TAG, logString);
            }
            ExampleUtil.showToast(logString, getApplicationContext());
        }
    };

    /**
     * 定位加获取天气数据
     */
    public void getLocation() {
        //获取Location
        String serviceName = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) getSystemService(serviceName); // 查找到服务信息

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, mLocationListener01);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, mLocationListener01);
    }

    public LocationListener mLocationListener01 = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            updateToNewLocation(location);
        }

        @Override
        public void onProviderDisabled(String provider) {
            updateToNewLocation(null);
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    };

    private void updateToNewLocation(Location location) {
        if (location != null) {
            getWeather(location.getLongitude() + "", location.getLatitude() + "");
        }
    }

    public void removeUpdate() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        locationManager.removeUpdates(mLocationListener01);
    }

    /**
     * 获取天气数据
     *
     * @param lng
     * @param lat
     */
    public void getWeather(String lng, String lat) {
        String url = "http://route.showapi.com/9-5";

        Map<String, String> formMap = new HashMap<>();
        formMap.put("showapi_appid", "44200");
        formMap.put("showapi_sign", "38a20ac8b1974dcb965cc4a419834671");
        formMap.put("from", "5");
        formMap.put("lng", lng);
        formMap.put("lat", lat);
        formMap.put("needMoreDay", "0");
        formMap.put("needIndex", "0");
        formMap.put("needHourData", "0");
        formMap.put("need3HourForcast", "0");
        formMap.put("needAlarm", "0");
        OkHttpUtils.post()
                .url(url)
                .params(formMap)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        ForLog.i(TAG, e.getMessage());
                        ForToast.showToast(R.string.intent_error);
                    }

                    @Override
                    public void onResponse(String response) {
                        ForLog.i(TAG + "getWeather", response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String status = jsonObject.getString("showapi_res_code");
                            if ("0".equals(status)) {
                                WeatherBean weatherBean = new Gson().fromJson(response, WeatherBean.class);
                                String weatherCode = weatherBean.getShowapi_res_body().getF1().getDay_weather_code();
                                if (weatherCode.equals("00") || weatherCode.equals("99")) {
                                    imageView_main_top_weather.setImageResource(R.drawable.nat_qing_n);
                                } else if (weatherCode.equals("01") ||
                                        weatherCode.equals("02") ||
                                        weatherCode.equals("18") ||
                                        weatherCode.equals("20") ||
                                        weatherCode.equals("29") ||
                                        weatherCode.equals("30") ||
                                        weatherCode.equals("31") ||
                                        weatherCode.equals("53")) {
                                    imageView_main_top_weather.setImageResource(R.drawable.nat_yintian_n);
                                } else {
                                    imageView_main_top_weather.setImageResource(R.drawable.nat_yutian_n);
                                }
                                textView_main_top_weather.setText(weatherBean.getShowapi_res_body().getF1().getDay_air_temperature() + "℃");
                                //关闭监听
                                removeUpdate();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

    }

    public void getMainFragmentRefreshGuanzhu(boolean bool, Web_forum_changeBean web_forum_changeBean) {
        if (bool) {
            main_circleFragment.getRefreshDate(web_forum_changeBean);
        } else {
            main_forumFragment.getRefreshDate(web_forum_changeBean);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == TAG_PUBLISH_CIRCLE) {
                main_circleFragment.getMain_FriendCircleData(1, 10);
            }
            if (requestCode == TAG_PUBLISH_FORUM) {
                main_forumFragment.getMain_ForumData(1, 10);
            }
            if (requestCode == TAG_FORUM) {
                Web_forum_changeBean web_forum_changeBean = (Web_forum_changeBean) data.getSerializableExtra("web_forum_changeBean");

                main_forumFragment.getRefreshDate(web_forum_changeBean);
                main_circleFragment.getRefreshDate(web_forum_changeBean);
            }
            if (requestCode == TAG_CIRCLE) {
                Web_forum_changeBean web_forum_changeBean = (Web_forum_changeBean) data.getSerializableExtra("web_forum_changeBean");

                main_forumFragment.getRefreshDate(web_forum_changeBean);
                main_circleFragment.getRefreshDate(web_forum_changeBean);
            }
        }
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    long exitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ForToast.showToast("再按一次退出");
                exitTime = System.currentTimeMillis();
            } else {
                MyApplication.getInstance().exit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 是否是华为
     */
    public static boolean isHUAWEI() {
        return Build.MANUFACTURER.equals("HUAWEI");
    }

    //获取是否存在NavigationBar
    public static boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        try {
            Resources rs = context.getResources();
            int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
            if (id > 0) {
                hasNavigationBar = rs.getBoolean(id);
            }
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {

        }
        return hasNavigationBar;
    }

    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            /**
             注意：
             1.图片加载器由自己选择，这里不限制，只是提供几种使用方法
             2.返回的图片路径为Object类型，由于不能确定你到底使用的那种图片加载器，
             传输的到的是什么格式，那么这种就使用Object接收和返回，你只需要强转成你传输的类型就行，
             切记不要胡乱强转！
             */

            //Glide 加载图片简单用法
            Glide.with(context).load(path).into(imageView);

            //用fresco加载图片简单用法，记得要写下面的createImageView方法
            Uri uri = Uri.parse((String) path);
            imageView.setImageURI(uri);
        }
    }

    /**
     * 侧边栏分享弹框
     */
    public void getDialogShare() {
        dialog_share = new Dialog(this, R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(this).inflate(R.layout.diglog_set_shape, null);
        dialog_share.setContentView(view);
        Window dialogWindow = dialog_share.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 0;
        lp.width = getResources().getDisplayMetrics().widthPixels; // 宽度
        dialogWindow.setAttributes(lp);

        LinearLayout linearLayout_share_wechatFriend = (LinearLayout) view.findViewById(R.id.linearLayout_share_wechatFriend);
        LinearLayout linearLayout_share_wechatCircle = (LinearLayout) view.findViewById(R.id.linearLayout_share_wechatCircle);
        LinearLayout linearLayout_share_tencentCircle = (LinearLayout) view.findViewById(R.id.linearLayout_share_tencentCircle);

        linearLayout_share_wechatFriend.setOnClickListener(this);
        linearLayout_share_wechatCircle.setOnClickListener(this);
        linearLayout_share_tencentCircle.setOnClickListener(this);
    }

    /**
     * 侧边栏分享回调
     *
     * @param anEnum
     */
    private void ShareWeb(Enum anEnum) {
        UMImage thumb = new UMImage(this, R.mipmap.ic_launcher);
        UMWeb web = new UMWeb(HttpApi.SHARE_APP);
        web.setThumb(thumb);
        web.setDescription("为亿万用户提供个性化的每日育儿指导，不用搜索，不用导航，轻轻一点，每日育儿即可直接呈现");
        web.setTitle("下载撩娃APP，让育儿如此简单！");
        new ShareAction(this).withMedia(web).setPlatform((SHARE_MEDIA) anEnum).setCallback(new UMShareListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
                ForToast.showToast("后台正在玩儿命加载~~~");
            }

            @Override
            public void onResult(SHARE_MEDIA share_media) {
                ForToast.showToast("分享成功！");
            }

            @Override
            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                ForLog.i("throwable", "" + throwable.toString());
                ForToast.showToast("分享失败！");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {
                ForToast.showToast("取消分享！");
            }
        }).share();
    }

    /**
     * 消息通知数量，是否显示小红点
     */
    private void getSystemMessageAndTime() {
        int unReadMessage = PushMessageManager.getUnReadMessage();
        List<PushMessage> pushMessageList = PushMessageManager.queryAll();
        int msg_num = (ForPreference.getInt(ForContents.APP_NOTICE_MSG) > 0
                ? ForPreference.getInt(ForContents.APP_NOTICE_MSG) : 0)
                + pushMessageList.size();

        ForLog.i("xiaohongdian", "" + msg_num);

        imageView_rightmenu_notice.setImageResource(msg_num > 0 ? R.drawable.icon_xiaoxihongdian_n : R.drawable.nat_xiaoxi_n);
    }

    @Override
    protected void onStart() {
        super.onStart();
        //开始轮播
        banner_main_event.startAutoPlay();
    }

    @Override
    protected void onStop() {
        super.onStop();
        //结束轮播
        banner_main_event.stopAutoPlay();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        bool_downAPK = false;

        if (ForPreference.getString(ForContents.USER_PHONE).equals("") ||
                ForPreference.getString(ForContents.USER_PHONE) == null) {
            //没有娃
            textView_main_top_changewa.setText(R.string.main_select_wa);
        } else {
            //有娃
            textView_main_top_changewa.setText(ForPreference.getString(ForContents.WA_nickname));

            /**
             * 刷新侧边栏数据
             */
            Glide
                    .with(this)
                    .load(ForPreference.getString(ForContents.USER_HEADERURL))
                    .transform(new GlideCircleTransform(MainActivity.this))
                    .crossFade()
                    .error(R.drawable.img_baobaotouxiang)
                    .into(imageViewRightHeaderimg);
            textViewRightUserName.setText(ForPreference.getString(ForContents.USER_NAME));//设置昵称
            textViewRightBabytime.setText(ForPreference.getString(ForContents.WA_DAY));//设置孩子提示语

            textView_right_my_circle.setText(ForPreference.getInt(ForContents.USER_my_circle) + "");//设置每日随笔数
            textViewRightCollectionNum.setText(ForPreference.getInt(ForContents.USER_COLLECTION) + "");//设置收藏数量
            textViewRightFollow.setText(ForPreference.getInt(ForContents.USER_follow) + "");//设置关注数量
            textViewRightFans.setText(ForPreference.getInt(ForContents.USER_fans) + "");//设置粉丝数量
            textView_right_my_forum.setText(ForPreference.getInt(ForContents.USER_forum_num) + "");

            if (ForPreference.getBoolean(ForContents.DELETE_WA_ID)) {
                //是否删除娃
                getListData();
                ForPreference.putBoolean(ForContents.DELETE_WA_ID, false);
            }

            if (ForPreference.getBoolean(ForContents.WHERE_WA_ID)) {
                //是否切换宝宝
                getMainData(true);
                mainChangeWaAdapter.notifyDataSetChanged();
                ForPreference.putBoolean(ForContents.WHERE_WA_ID, false);
            }

            if (ForPreference.getBoolean(ForContents.WA_BIRTHDAY_BOOL)) {
                //是否修改娃生日
                getMainData(true);
                ForPreference.putBoolean(ForContents.WA_BIRTHDAY_BOOL, false);
            }

            if (ForPreference.getBoolean(ForContents.DIARY_SHARE_BOOL)) {
                //用户随笔是否分享，是否刷新宝妈圈
                ForPreference.putBoolean(ForContents.DIARY_SHARE_BOOL, false);
//            getMain_FriendCircleData(1, 10);
            }

            if (waBeanList != null) {
                //刷新默选娃
                for (int i = 0; i < waBeanList.size(); i++) {
                    if (ForPreference.getString(ForContents.WA_DEFAULT_ID).equals(waBeanList.get(i).getId() + "")) {
                        waBeanList.get(i).setNickName(ForPreference.getString(ForContents.WA_nickname));
                    }
                }
                mainChangeWaAdapter.notifyDataSetChanged();
            }

            if (mainBean != null) {
                if (mainBean.getHomeinfo().getFiletype() == 0) {
                    Glide.with(MainActivity.this)
                            .load(ForPreference.getString(ForContents.WA_headerimg_url))
                            .transform(new GlideCircleTransform(MainActivity.this))
                            .crossFade()
                            .error(R.drawable.img_baobaotouxiang)
                            .into(imageView_main_top_liao);
                }
            }

            //侧边栏消息通知小红点
            getSystemMessageAndTime();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mWaveHelper.cancel();//关闭
        waveHelper_index.cancel();//关闭
        MobclickAgent.onPause(this);       //结束统计时长
        MobclickAgent.onPageEnd("首页");
    }

    @Override
    protected void onResume() {
        super.onResume();
        mWaveHelper.start();//启动
        waveHelper_index.start();//启动
        MobclickAgent.onPageStart("首页");
        MobclickAgent.onResume(this);       //开始统计时长
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 记录APP版本号
     */
    private void recordAppVersion() {
        PackageManager manager = getPackageManager();
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        if (info == null || "".equals(info)) {
            ForPreference.putString(ForContents.APP_VERSION, "null");
        } else {
            String versionName = info.versionName;
            ForPreference.putString(ForContents.APP_VERSION, versionName);
        }
    }

    /**
     * 记录用户机型
     */
    private void recordPhoneMode() {
        String model = android.os.Build.MODEL;
        String manufacturer = android.os.Build.MANUFACTURER;
        ForPreference.putString(ForContents.USER_PHONE_MODEL, "手机厂家" + manufacturer + " 型号" + model);
    }

    /**
     * 记录用户手机系统版本
     */
    private void recordPhoneSystemLevel() {
        String release = Build.VERSION.RELEASE;
        ForPreference.putString(ForContents.USER_PHONE_SYSTEM_LEVEL, "系统版本" + release);
    }
}
